package com.ruoyi.common.utils;

import org.apache.poi.ss.usermodel.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ExcelUtil {

    public static List<List<String>> parseExcel(MultipartFile file) throws IOException {
        List<List<String>> data = new ArrayList<>();

        // 根据文件类型创建Workbook
        Workbook workbook = WorkbookFactory.create(file.getInputStream());

        // 获取第一个Sheet
        Sheet sheet = workbook.getSheetAt(0);

        // 遍历行
        for (Row row : sheet) {
            List<String> rowData = new ArrayList<>();

            // 遍历单元格
            for (Cell cell : row) {
                rowData.add(getCellValueAsString(cell));
            }
            data.add(rowData);
        }

        workbook.close();
        return data;
    }

    private static String getCellValueAsString(Cell cell) {
        if (cell == null) return "";

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue().trim();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    // 防止科学计数法
                    return String.format("%.0f", cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }
}
